package com.jn.mvp.views;

import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.jn.mvp.R;
import com.jn.mvp.base.BaseActivity;
import com.jn.mvp.common.ChooseDialog;
import com.jn.mvp.contract.RegionContract;
import com.jn.mvp.entity.RegionEntity;
import com.jn.mvp.presenter.RegionPresenter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RegionActivity extends BaseActivity
        implements RegionContract.IRegionView, View.OnClickListener {
    private Button mButtonGet;
    private TextView mText;
    private RegionContract.IRegionPresenter mPresenter;

    @Override
    public int getLayoutId() {
        return R.layout.activity_region;
    }

    @Override
    public void init() {
        mPresenter = new RegionPresenter(this, this);
        mButtonGet = findViewById(R.id.button_get);
        mText = findViewById(R.id.text);
        mButtonGet.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.button_get) {
            mPresenter.getData("0");
            mText.setText("");
        }
    }

    @Override
    public void showData(List<RegionEntity.ResultDTO> list) {
        showDialog(list);
    }

    @Override
    public void onHttpLoading(boolean loading) {
        if (loading) {
            showLoading();
        } else {
            dismissLoading();
        }
    }

    @Override
    public void onHttpFail(String... msg) {
        if (msg != null && msg.length > 0) {
            showToast(msg[0]);
        }
    }

    @Override
    public void onHttpTimeout() {
        showToast("请求超时");
    }

    @Override
    public void onHttpTokenExpiration() {
        showToast("token 过期，请重新登录");
    }

    private void showDialog(List<RegionEntity.ResultDTO> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        int size = list.size();
        String[] names = new String[size];
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < size; i++) {
            RegionEntity.ResultDTO region = list.get(i);
            String dz = region.getName();
            names[i] = dz;
            map.put(dz, region.getId());
        }
        ChooseDialog regionDialog = new ChooseDialog(this, new ChooseDialog.OnButtonClickListener() {
            @Override
            public void confirm(String address) {
                String code = map.get(address);
                mText.setText(mText.getText() + " " + address);
                mPresenter.getData(code);
            }

            @Override
            public void close() {

            }
        });
        regionDialog.setTitle("获取行政区");
        regionDialog.setText(names);
        regionDialog.setBetween(0, size - 1);
        regionDialog.show();
    }
}
